# -*- encoding:UTF-8 -*-
# desc: 回传epkg包,暂时先回传到z9（暂时使用shell中已经实现的方法）
# created time : 20250117

import argparse
import subprocess
import sys
import os
import glob


def after_deal(rpm_dir, epkg_dir):
    """后处理"""
    # 清理rpm文件
    for rpm in os.listdir(rpm_dir):
        rpm_file_path = os.path.join(rpm_dir, rpm)
        if os.path.isfile(rpm_file_path):
            os.remove(rpm_file_path)
    # 清理epkg文件
    if os.path.isfile(epkg_dir):
        os.remove(epkg_dir)


def get_all_files(directory):
    # 使用 os.walk 遍历目录
    all_files = [] # 相对目录
    for root, dirs, files in os.walk(directory):
        for file in files:
            full_path = os.path.join(root, file)

            relative_path = os.path.relpath(full_path, directory)
            all_files.append(os.path.join(relative_path))
    return all_files


def postback_epkg(args):
    """
        回传epkg包
    """
    epkg_name_list = []
    result_root = args.postback_dir
    epkgdir = args.epkg_dir
    rpm_dir = args.rpm_dir
    # epkg_dir = "{0}/store/*/*".format(epkgdir)
    # match_file = glob.glob(epkgdir)
    match_file = get_all_files(epkgdir)
    script = "{0}/lib/upload.sh".format(os.environ.get("LKP_SRC"))
    for file_name in match_file:
        if file_name.endswith("epkg"):
                full_path = "{0}/{1}".format(epkgdir, file_name)
                epkg_dirname = os.path.dirname(file_name)
                result = subprocess.run(f"source {script} && "
                                        f"upload_one_curl {full_path} {result_root}/{epkg_dirname}",
                                        shell=True,
                                        stdout=sys.stdout,
                                        stderr=sys.stderr)
                if result.returncode != 0:
                    print("回传失败：{0}".format(result.stderr))
                    return -1
                else:
                    epkg_name_list.append(file_name)
                    print(f"{file_name}回传完成")
                # 后处理，回传之后删除执行机对应rpm包和epkg包
                ret = after_deal(rpm_dir, full_path)
        else:
            continue
    return 0


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="epkg回传")
    parser.add_argument("-postback_dir", required=True, default="",
                        help="回传路径")
    parser.add_argument("-epkg_dir", required=True, default="",
                        help="epkg包存放目录")
    parser.add_argument("-rpm_dir", required=True, default="",
                        help="rpm包存放目录")

    args = parser.parse_args() 
    ret = postback_epkg(args)
    if ret != 0:
        sys.exit(1)
